package com.ouheng.shop.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ouheng.common.controller.BaseController;
import com.ouheng.common.domain.DictDO;
import com.ouheng.common.service.DictService;
import com.ouheng.common.utils.ExportExcel;
import com.ouheng.common.utils.ImportExcelUtil;
import com.ouheng.common.utils.KuaidiRestfull;
import com.ouheng.common.utils.PageUtils;
import com.ouheng.common.utils.Query;
import com.ouheng.common.utils.R;
import com.ouheng.common.utils.StringUtils;
import com.ouheng.shop.domain.OhOrderDO;
import com.ouheng.shop.service.OhOrderService;

import net.sf.json.JSONObject;

/**
 * 订单
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-09-06 09:49:40
 */
 
@Controller
@RequestMapping("/shop/ohOrder")
public class OhOrderController extends BaseController{
	@Autowired
	private OhOrderService ohOrderService;
	
	@Autowired
	private DictService dictService;
	
	@GetMapping()
	@RequiresPermissions("shop:ohOrder:ohOrder")
	String OhOrder(){
	    return "shop/ohOrder/ohOrder";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("shop:ohOrder:ohOrder")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OhOrderDO> ohOrderList = ohOrderService.list(query);
		List<OhOrderDO> OhOrderDOList2 = new ArrayList<>();
		for (OhOrderDO ohOrderDO : ohOrderList) {
			ohOrderDO.setProductNameAndNumber(ohOrderService.orderProductNameAndNumber(ohOrderDO.getId()));
			OhOrderDOList2.add(ohOrderDO);
		}
		int total = ohOrderService.count(query);
		PageUtils pageUtils = new PageUtils(OhOrderDOList2, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("shop:ohOrder:add")
	String add(){
	    return "shop/ohOrder/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("shop:ohOrder:edit")
	String edit(@PathVariable("id") Long id,Model model){
		List<DictDO> listDict = dictService.listByType("logistics");
		model.addAttribute("listDict", listDict);
		OhOrderDO ohOrder = ohOrderService.get(id);
		ohOrder.setStatus("3");
		model.addAttribute("ohOrder", ohOrder);
	    return "shop/ohOrder/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("shop:ohOrder:add")
	public R save( OhOrderDO ohOrder){
		if(ohOrderService.save(ohOrder)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("shop:ohOrder:edit")
	public R update( OhOrderDO ohOrder){
//		ohOrder.setUser(getUser());
		ohOrderService.update(ohOrder);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("shop:ohOrder:remove")
	public R remove( Long id){
		if(ohOrderService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("shop:ohOrder:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		ohOrderService.batchRemove(ids);
		return R.ok();
	}
	
	/**
	 * 导出excel
	 * @Title: downloadAllClassmate   
	 * @Description: TODO(导出excel)   
	 * @param: @param ids
	 * @param: @param response
	 * @param: @throws IOException      
	 * @return: void      
	 * @throws
	 */
	@GetMapping(value = "UserExcelDownloads")
	@RequiresPermissions("shop:ohOrder:UserExcelDownloads")
    public void downloadAllClassmate(Long[] ids,HttpServletRequest request,HttpServletResponse response)throws IOException{
		HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("订单信息");
        String[] headers = {"物流订单号(必填)","物流中文名称(必填)","物流英文名称(必填)","订单号","订单商品", "买家姓名", "买家收货省","买家收货市","买家收货区","买家收货地址"," 买家手机号码"};
		String fileName="商品订单";
        ExportExcel.ExportExcel(headers, workbook, sheet, fileName, request, response);
        //设置列宽
        sheet.setDefaultColumnWidth(24);
        List<OhOrderDO> classmateList = ohOrderService.listOhOrderByIds(ids);
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        //headers表示excel表中第一行的表头
        //在表中存放查询到的数据放入对应的列
        for (OhOrderDO ohOrderDO : classmateList) {
        	String[] address = ohOrderDO.getAddress().split("-");
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue("");
            row1.createCell(1).setCellValue("");
            row1.createCell(2).setCellValue("");
            row1.createCell(3).setCellValue(ohOrderDO.getNumber());
            row1.createCell(4).setCellValue(ohOrderService.orderProductNameAndNumber(ohOrderDO.getId()));
            row1.createCell(5).setCellValue(ohOrderDO.getConsignee());
            row1.createCell(6).setCellValue(address[0]);
            row1.createCell(7).setCellValue(address[1]);
            row1.createCell(8).setCellValue(address[2]);
            row1.createCell(9).setCellValue(address[3]);
            row1.createCell(10).setCellValue(ohOrderDO.getPhone());
            rowNum++;
        }

        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
	
	/**
	 * 导入EXCEL
	 * @Title: importExcel   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param request
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: R      
	 * @throws
	 */
	@PostMapping(value = "importExcel")
	@ResponseBody
	@RequiresPermissions("shop:ohOrder:importExcel")
    public R importExcel(HttpServletRequest request)throws Exception {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		InputStream in =null;  
        List<List<Object>> listob = null;  
        MultipartFile file = multipartRequest.getFile("file");  
        if(file.isEmpty()){  
            throw new Exception("文件不存在！");  
        }
        in = file.getInputStream();  
        listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
        in.close(); 
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i); 
            String a1 = String.valueOf(lo.get(0));
            String a2 =String.valueOf(lo.get(1));
            String a3 =String.valueOf(lo.get(2));
            
            if(StringUtils.isBlank(a1)){
            	return R.error(0,"物流单号不能为空");
            }
            if(StringUtils.isBlank(a2)){
            	return R.error(0,"物流中文名称不能为空");
            }
			if(StringUtils.isBlank(a3)){
				return R.error(0,"物流英文名称不能为空");
			}
        } 
        
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i); 
            String a1 = String.valueOf(lo.get(0));
            String a2 =String.valueOf(lo.get(1));
            String a3 =String.valueOf(lo.get(2));
            String a4 =String.valueOf(lo.get(3));
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("number", a4);
    		List<OhOrderDO> ohOrderList = ohOrderService.list(map);
    		if (!ohOrderList.isEmpty()) {
    			OhOrderDO ohOrderDO = ohOrderList.get(0);
    			if("2".equals(ohOrderDO.getStatus())||"3".equals(ohOrderDO.getStatus())){
    				ohOrderDO.setLogisticsnumber(a1);
    				ohOrderDO.setLogisticsname(a2);
    				ohOrderDO.setLogisticsename(a3);
        			ohOrderDO.setStatus("3");
        			ohOrderService.update(ohOrderDO);
    			}
			}
        }
        return R.ok();
    }
	
	/**
	 * 查询物流信息
	 * @Title: checkLogist   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param id
	 * @param: @param model
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@GetMapping("/logistics/{id}")
	public String logistics(@PathVariable("id")Long id,Model model){
		model.addAttribute("id", id);
		return "shop/ohOrder/logistics";
	}
	@GetMapping("/checkLogist/{id}")
	@ResponseBody
	public Map<String, Object> checkLogist(@PathVariable("id")Long id,Model model){
		Map<String, Object> map = new HashMap<>();
		OhOrderDO ohOrderDO = ohOrderService.get(id);
		//查询列表数据
		Map<String, Object> params = new HashMap<>();
		params.put("com",ohOrderDO.getLogisticsename().trim());
		params.put("num",ohOrderDO.getLogisticsnumber().trim());
		String resp=KuaidiRestfull.common(params);
		JSONObject json = JSONObject.fromObject(resp);
		map.put("data", json);
		return map;
	}
	
	
	@GetMapping("/listBystatus")
	@RequiresPermissions("shop:ohOrder:ohOrder")
	String OhOrder(Model model){
	    return "shop/ohOrder/ohOrder2";
	}
	
	@ResponseBody
	@GetMapping("/list1")
	@RequiresPermissions("shop:ohOrder:ohOrder")
	public PageUtils list1(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OhOrderDO> ohOrderList = ohOrderService.listByStatus(query);
		List<OhOrderDO> OhOrderDOList2 = new ArrayList<>();
		for (OhOrderDO ohOrderDO : ohOrderList) {
			ohOrderDO.setProductNameAndNumber(ohOrderService.orderProductNameAndNumber(ohOrderDO.getId()));
			OhOrderDOList2.add(ohOrderDO);
		}
		int total = ohOrderService.countByStatus(query);
		PageUtils pageUtils = new PageUtils(OhOrderDOList2, total);
		return pageUtils;
	}
	
}
